<?php
/**
 * Description: 获取学习状态统计
 * User: devforma
 * Date: 15/1/7
 * Time: 15:35
 */

class GetPlanSummary implements iController {

    private $userId, $userIdField, $taskType=array(), $category=array();
    
    /**
     * api请求处理主函数
     * 
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;
        
        $u = validateUser($queryArgs);
        if ($u == 0 || $u == 3)
            return genOutput(1000);
        
        if ($u == 1) {
            $this->userIdField = 'user_id';
            $this->userId = $queryArgs['user_id'];
        } elseif ($u == 2) {
            $this->userIdField = 'guest_id';
            $this->userId = $queryArgs['guest_id'];
        } else {
            return genOutput(1000);
        }
        
        //获取用户上岸计划的信息
        $sql = "SELECT * FROM `{$uddb->userDPData}` WHERE `{$this->userIdField}`=:user";
        $planData = $uddb->getRow($sql, array(':user' => $this->userId));
        
        //用户未开启上岸计划
        if (empty($planData)) return genOutput(1000);
        
        //获取任务类型设置
        $taskTypeData = $uddb->getResults("SELECT * FROM `{$uddb->confPlanType}` WHERE 1");
        foreach ($taskTypeData as $row) {
            $this->taskType["$row->type_id"] = $row->type_name; //由type_id获取信息
            $this->taskType["$row->type_name"] = $row->type_id; //由名称获取信息
        }
        
        return genOutput(1, array(
            'summary' => array(
                'shizheng_count' => $this->getShizhengCount(),
                'category' => $this->getCategoryInfo(),
                'recent' => $this->getRecentInfo($planData)
            )
        ));
    }

    /**
     * 获取各分类的学习情况
     * 
     * @return array
     */
    private function getCategoryInfo() {
        global $uddb;
        
        //获取分类信息
        $categoryData = $uddb->getResults("SELECT * FROM `{$uddb->questionCategory}` WHERE 1");
        if (empty($categoryData)) return array();
        
        $category = array();
        foreach ($categoryData as $cat) {
            $this->category["$cat->category_id"] = $cat;
            $this->category["$cat->category_name"] = $cat;
            $category["$cat->category_id"] = array(
                'name' => mb_substr($cat->category_name, 0, 2, 'UTF-8'),
                'description' => $cat->category_desc,
                'total' => 0,
                'right' => 0
            );
        }
        
        //获取用户做过的题目学习情况
        $sql = "SELECT * FROM `{$uddb->userTests}` WHERE `{$this->userIdField}`=:user";
        $questions = $uddb->getResults($sql, array(':user' => $this->userId));
        
        if (!empty($questions)) { //没有做题记录
            foreach ($questions as $q) {
                if (isset($category["$q->category_id"])) {
                    //统计该分类总体量和做对的题量
                    $category["$q->category_id"]['total']++;
                    if (!$q->is_wrong) {
                        $category["$q->category_id"]['right']++;
                    }
                }
            }
        }
        
        return array(
            $category[4],
            $category[5],
            $category[2],
            $category[1],
            $category[3]
        );
    }

    /**
     * 获取最近7天的各天任务总数
     * @param Object $planData 上岸计划信息记录
     * @return array
     */
    private function getRecentInfo($planData) {
        global $uddb;
        
        //获取当天完成的任务数
        $today = date('Y-m-d');
        $startOfToday = strtotime($today);

        $firstDay = date('Y-m-d', strtotime($planData->create_time)); //用户第一天的日期
        
        //今天距离第一天的天数（算第一天和今天）
        $days = ($startOfToday - strtotime($firstDay))/(24*60*60) + 1; 
        if ($days > 7) {
            $days = 7;
            $daysBeforeTimestamp = $startOfToday - 60*60*24*($days-1);
        } else {
            //6天前（一共要7天，不算今天，所以前推6天）的日期的时间戳
            $daysBeforeTimestamp = strtotime($firstDay);
        }
        
        //获取最近几天完成的任务数
        $sql = "SELECT * FROM `{$uddb->recentMissionInfo}`
                WHERE `action_type`=1 AND `available`=1 AND `{$this->userIdField}`=:user";
        $recentTasks = $uddb->getResults($sql, array(':user'=>$this->userId));
        
        //获取历史任务
        $sql = "SELECT * FROM `{$uddb->historyMissionAction}`
                WHERE `{$this->userIdField}`=:user
                AND UNIX_TIMESTAMP(`action_time`)>{$daysBeforeTimestamp}";
        $history = $uddb->getResults($sql, array(':user' => $this->userId));

        $sql = "SELECT COUNT(DISTINCT(`mission_id`)) FROM `dp_history_mission_action`
                WHERE `{$this->userIdField}`=:user
                AND UNIX_TIMESTAMP(`action_time`)<={$daysBeforeTimestamp}";
        $baseCount = $uddb->getVar($sql, array(':user' => $this->userId));

        //历史任务滤重
        $existMissionIds = [];
        $historyTasks = [];
        foreach ($history as $mission) {
            if (in_array($mission->mission_id, $existMissionIds, true)) continue;

            $historyTasks[] = $mission;

            $existMissionIds[] = $mission->mission_id;
        }

        $allTasks = array_merge($recentTasks, $historyTasks); //合并成连续的

        $dateArray = self::genDateArray($today, $days); //生成连续n天的日期数组

        //计算历史6天的任务完成数量
        foreach ($allTasks as $task) {
            $date = date('Y-m-d', strtotime($task->action_time));
            if (isset($dateArray[$date]))
                $dateArray[$date]++;
        }

        //计算直到每一天的任务总数
        $total = 0;
        ksort($dateArray); //日期从低到高排序
        $result = array();
        foreach ($dateArray as $date => $count) {
            $count += $total;
            $total = $count;

            $result[] = array(
                'date' => $date,
                'count' => intval($count) + $baseCount
            );
        }
        
        return $result;
    }

    /**
     * 生成连续的日期-任务数组，key为日期，value为该日期对应的任务数量
     * @param string $dateStr 从哪天算起
     * @param int $days 从今天往前数多少天
     * @return array
     */
    private static function genDateArray($dateStr, $days) {
        $dateArray = array();
        $dateArray["$dateStr"] = 0;
        $date = date_create($dateStr);

        for ($i = 0; $i < $days - 1; $i++) {
            date_sub($date, date_interval_create_from_date_string("1 day"));
            $dateStr = date_format($date, 'Y-m-d');
            $dateArray["$dateStr"] = 0; //每个日期对应的value为任务数量，初始化为0
        }

        return $dateArray;
    }

    /**
     * 获取历史完成的时政热点数量
     * @return int
     */
    private function getShizhengCount() {
        global $uddb;
        
        $sql = "SELECT COUNT(*) FROM `{$uddb->recentMissionInfo}`
                WHERE `{$this->userIdField}`=:user AND `action_type`=1
                AND `mission_type`={$this->taskType['时政热点']}";
        $recent = $uddb->getVar($sql, array(':user' => $this->userId));
        
        $sql = "SELECT COUNT(*) FROM `dp_history_mission_action`
                WHERE `{$this->userIdField}`=:user
                AND `mission_type`={$this->taskType['时政热点']}";
        $history = $uddb->getVar($sql, array(':user' => $this->userId));
        
        return $recent + $history;
    }
}